<script setup>
import { ref, reactive, onMounted, inject, provide, computed, watch, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { scrollToFormError } from '@/utils/common';
import SmtHeader from '@/layout/SmtHeader.vue';
import SmtFooter from '@/layout/SmtFooter.vue';
import Sections from '@/components/Sections/index.vue';
import View3D from '@/components/3Dview/3Dview.vue';
import Tips from '@/components/Tips/index.vue';
import UpLoadBoom from '@/components/upLoad/UpLoadBoom.vue';
import UpLoadCoordinate from '@/components/upLoad/UpLoadCoordinate.vue';
import { getMallFileData, uploadDocFile } from '@/server/api/file';
import SelectPcbOrderDialog from './components/SelectPcbOrderDialog.vue';
import BomSelectModal from './components/BomSelectModal.vue';
import ConfirmBox from './components/ConfirmBox.vue';
import CoordinateConfirmDialog from './components/CoordinateConfirmDialog.vue';
import BoomConfirmDialog from './components/BoomConfirmDialog.vue';
import useOrderStore from '@/store/modules/order';
import GroupSelectTree from '@/components/GroupSelectTree/index.vue';
import useAppStore from '@/store/modules/app';
import { standardDocumentsPath } from '@/server/api/file';
import {
  listAddress,
  addSmt,
  gerberFilelist,
  queryCraftsCategoryList,
  getDictTypeList,
  crmPcbaOrderCalculationAmountAPI,
  getPcbaServiceCategoryList,
  getExpressCompanyList,
  queryOmsProductionMaterialBatchList,
  getBomMatchListStatisticsData,
  getBomProcessServiceQuotation,
} from '@/server/api/biz.js';
import { scrollToSection, downloadFile } from '@/utils/common.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import { conforms } from 'lodash';
import { getMallFileDownLoadPath } from '@/server/api/file';
import { product } from '../../../server/apiUrl/biz';

const orderStore = useOrderStore();
const appStore = useAppStore();

// 选中的工艺服务信息
const selectedListMap = ref({});
provide('selectedListMap', selectedListMap);
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
const images = inject('images');
const formRef = ref();
const router = useRouter();
const route = useRoute();
const data = reactive({
  gerberFileData: [], // gerber文件列表，用于3d渲染
  craftsList: [], // PCB工艺信息
  smtOptionList: [], // SMT选项列表
  productList: [], // 板材类型
  baseServieList: [], // 基础服务
  craftServideList: [], // 定制服务
  customizedServiceList: [], // 工艺服务
  boardLayersSum: 0,
});

// 智能报价账单信息
const billInfo = ref({});

const visible = ref(false);
const bomVisible = ref(false);
const boomConfrimVisible = ref(false); // boom确认弹窗
const coordinateConfrimVisible = ref(false); // 焊点确认弹窗
const isShowBomProgress = ref(false);
const isShowCoordinateProgress = ref(false);
const userUploadFileName = ref();
const userUploadFilePath = ref();
const craftsRef = ref(null);

const tableData = ref([]);
// smt订单信息
const ruleForm = reactive({
  productId: '', // 产品Id
  productName: '', // 产品名称
  batchYearLimit: 0, // 接受批次
  isUseAlternative: 1, // 是否接受替代料 1接受，2不接受、
  matchType: 1, // 匹配方式1快速匹配，2深度匹配
  smtLayer: '1', // 贴片层(1全贴，2顶层，3底层,默认1全贴)
  ordetrNumber: '', // 贴片数量
  productType: '1', // 产品类型
  pcbLength: '', // 板子长度
  pcbWidth: '', // 板子宽度
  agreement: false, // 是否同意
  productName: '', // 板材类型名称
  craftsCategory: [], // 选中的工艺数据
  serviceCategory: [], // 选中的服务数据
  whetherPatch: '1', // 是否贴片'
  gerberFileId: null, // Gerber文件id
  gerberFileName: '', // Gerber文件name
  renderData: [], // gerber文件列表，用于3d渲染
});
const batchList = ref([]); // 生产批次列表

// 文件信息
const fileInfo = reactive({
  gerberInfo: null,
  boomInfo: null,
  coordinateInfo: null,
});

// 用户协议链接
const agreementUrl = computed(() => {
  const lang = appStore.language;
  switch (lang) {
    case 'en':
      return window.location.origin + '/#/user-agreement/en_US';
    default:
      return window.location.origin + '/#/user-agreement';
  }
});

const boomConfirm = ref(false); // boom确认
const coordinateConfirm = ref(false); // 坐标文件确认

const viewRef = ref(); // 3d viewer
const rules = reactive({
  orderNumber: [
    {
      required: true,
      message: t('mall.enter_smt_quantity'),
      trigger: 'change',
    },
  ],
  productId: [
    {
      required: true,
      message: t('mall.choose_material_type'),
      trigger: 'change',
    },
  ],
  isUseAlternative: [
    {
      required: true,
      message: t('mall.choose_substitute_material'),
      trigger: 'change',
    },
  ],
  batchYearLimit: [
    {
      required: true,
      message: t('mall.choose_batch'),
      trigger: 'change',
    },
  ],
});

onMounted(() => {
  initData();
});

// 初始化数据
const initData = () => {
  getFiledList();
  getBatchOptionList();
  getHomeQueryData();
  // pcb订单跳转过来，需默认选中ibe定制
  const previousRoute = appStore.previousRoute;
  if (previousRoute.name === 'pcb') {
    ruleForm.productType = '2';
    if (Object.keys(orderStore.pcbOrderInfo).length > 0) {
      ruleForm.pcbLength = orderStore.pcbOrderInfo.pcbLength;
      ruleForm.pcbWidth = orderStore.pcbOrderInfo.pcbWidth;
    }
  }
};

// PCB费用
const pcbAmount = computed(() => {
  if (ruleForm.productType === '2') {
    const pcbOrderInfo = orderStore.pcbOrderInfo.billInfo;
    if (pcbOrderInfo) {
      return `${pcbOrderInfo.craftsServiceAmount}`;
    } else {
      return 0;
    }
  } else {
    return 0;
  }
});

const estimatedCost = computed(() => {
  const value = billInfo.value.payCurrencyTaxAmount
    ? Number(pcbAmount.value) + Number(billInfo.value.payCurrencyTaxAmount)
    : Number(pcbAmount.value);
  return value;
});

// 计价描述
const pricingDesc = computed(() => {
  const pcbOrderInfo = orderStore.pcbOrderInfo;
  const info = [];
  if (pcbOrderInfo.pcbLength && pcbOrderInfo.pcbWidth) {
    info.push(`${pcbOrderInfo.pcbLength}X${pcbOrderInfo.pcbWidth}cm`);
  }
  // 获取板层信息
  const layerInfo = pcbOrderInfo.craftsCategory.find((item) => item.mainCategory === 1);
  if (layerInfo) {
    info.push(`${t('mall.layer_board', { num: layerInfo.craftsName })}`);
  }
  // 板子数量
  if (pcbOrderInfo.orderNumber) {
    info.push(`${t('mall.sets', { num: pcbOrderInfo.orderNumber })}`);
  }
  return info.join(',');
});

// 工艺服务必填校验规则
const formItemRule = (item, label) => {
  return [
    {
      required: item.requiredSelect === 1,
      message: `${t('mall.please_select')}${item[label]}`,
      trigger: 'blur',
    },
  ];
};

// 首页或者pcb回显数据
const getHomeQueryData = () => {
  const { orderNumber, smtLayer, bomName, fileSerial, bomFileId, patchNum } = route.query;
  if (smtLayer) {
    ruleForm.smtLayer = smtLayer;
  }
  if (orderNumber && Object.keys(orderStore.pcbOrderInfo).length) {
    ruleForm.orderNumber = orderNumber;
  }
  if (bomName && fileSerial && bomFileId) {
    const boomInfo = {
      fileId: bomFileId,
      patchNum,
      name: bomName,
      fileSerial,
    };
    boomConfirm.value = true;
    fileInfo.boomInfo = boomInfo;
  }
  if (patchNum) {
    ruleForm.orderNumber = patchNum;
  }
};

// 获取产品名称
// watch(
//   () => ruleForm.productId,
//   (productId) => {
//     ruleForm.productName = data.productList.find((item) => item.categoryId === productId).name;
//   },
// );

/**
 * 获取表单字段
 * @param {*} row
 */
const getFiledList = () => {
  getProductList();
  getPcbCraftsCategoryList();
  getServiceListGroup();
  getSmtOptionList();
};

/**
 * 获取产品分类列表
 */
const getProductList = () => {
  getDictTypeList({
    businessType: 2,
  }).then((res) => {
    if (res.code === 200 && Array.isArray(res.data) && res.data.length > 0) {
      data.productList = res.data;
      ruleForm.productId = res.data[0].categoryId;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

/**
 * 获取物料生产批次信息
 */
const getBatchOptionList = () => {
  queryOmsProductionMaterialBatchList().then((res) => {
    if (res.code === 200) {
      batchList.value = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 默认回显数据
const getCachedDetail = () => {
  // 选中的服务工艺信息
  const smtSelectedInfo = orderStore.smtSelectedListMap;
  if (Object.keys(smtSelectedInfo).length) {
    selectedListMap.value = smtSelectedInfo;
  }
  // 选中的pcb订单信息
  const smtOrderInfo = orderStore.smtOrderInfo;
  console.log(' smtOrderInfo.smtOrderInfo', smtOrderInfo);
  if (Object.keys(smtOrderInfo).length > 0) {
    ruleForm.productType = smtOrderInfo.productType; // 产品类型
    ruleForm.smtLayer = smtOrderInfo.smtLayer; // 贴片层
    ruleForm.orderNumber = smtOrderInfo.orderNumber; // 贴片数量
    ruleForm.isUseAlternative = smtOrderInfo.isUseAlternative; // 	是否接受替代
    ruleForm.batchYearLimit = smtOrderInfo.batchYearLimit; // 	接受批次
    ruleForm.craftsCategory = smtOrderInfo.craftsCategory; // 选中的工艺数据
    ruleForm.serviceCategory = smtOrderInfo.serviceCategory; // 选中的服务数据
    ruleForm.pcbLength = smtOrderInfo.pcbLength; // 板子长度
    ruleForm.pcbWidth = smtOrderInfo.pcbWidth; // 板子宽度
    ruleForm.agreement = smtOrderInfo.agreement; // 是否同意
    ruleForm.productId = smtOrderInfo.productId; // 板材类型id
    ruleForm.productName = smtOrderInfo.productName; // 板材类型名称
    ruleForm.matchType = smtOrderInfo.matchType; // 匹配方式
    ruleForm.whetherPatch = smtOrderInfo.whetherPatch; // 是否贴片
    fileInfo.boomInfo = smtOrderInfo.boomInfo;
    fileInfo.coordinateInfo = smtOrderInfo.coordinateInfo;
    boomConfirm.value = smtOrderInfo.boomConfirm;
    coordinateConfirm.value = smtOrderInfo.coordinateConfirm;
    // 选择历史订单
    selectedOrderedPcbList.value = smtOrderInfo.selectedOrderedPcbList;
    if (ruleForm.productType === '3' && smtOrderInfo.gerberFileId) {
      getGerberFilelist(smtOrderInfo.gerberFileId);
      fileInfo.gerberInfo = smtOrderInfo.gerberInfo;
      ruleForm.gerberFileId = smtOrderInfo.gerberFileId; // Gerber文件id
      ruleForm.gerberFileName = smtOrderInfo.gerberFileName; // Gerber文件name
      ruleForm.renderData = smtOrderInfo.renderData;
    }
    // 重新报价
    getPcbQuote();
  } else {
    nextTick(() => {
      if (craftsRef.value) {
        craftsRef.value.forEach((ref) => {
          ref.clearSelectedValue();
          ref.initDefaultData();
        });
      }
    });
  }
};

/**
 * 获取PCB工艺分类列表
 */
const getPcbCraftsCategoryList = async () => {
  const res = await queryCraftsCategoryList({
    businessType: 2,
  });
  if (res.code === 200) {
    data.craftsList = res.data;
    getCachedDetail();
  } else {
    ElMessage.error(res.msg);
  }
};

/**
 * 获取定制服务列表组
 */
const getServiceListGroup = async () => {
  const res = await getPcbaServiceCategoryList({
    businessType: 2,
  });
  if (res.code === 200) {
    // 1 基础服务 2 定制服务 3 工艺服务
    data.baseServieList = res.data['1'] || [];
    data.customizedServiceList = res.data['2'] || [];
    data.craftServideList = res.data['3'] || [];
    getCachedDetail();
  } else {
    ElMessage.error(res.msg);
  }
};

/**
 * 获取SMT选项列表
 */
const getSmtOptionList = async () => {
  const res = await queryCraftsCategoryList({
    businessType: 2, // smt是2
  });
  if (res.code === 200) {
    data.smtOptionList = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

/**
 * 获取右侧报价信息
 */
const getPcbQuote = () => {
  // if (!fileInfo.boomInfo) {
  //   // ElMessage.error('请先上传BOM文件');
  //   return;
  // }
  // if (!fileInfo.coordinateInfo) {
  //   // ElMessage.error('请先上传坐标文件');
  //   return;
  // }
  // if (!ruleForm.smtLayer) {
  //   // ElMessage.error('请先选择贴片层');
  //   return;
  // }

  // 产品类型
  const productType = ruleForm.productType;
  if (productType === '1') {
    if (selectedOrderedPcbList.value.length === 0) {
      ElMessage.error(t('mall.select_placed_pcb_order'));
      return;
    }
  }

  const params = {
    business: 2,
    smtNumber: ruleForm.orderNumber,
    layer: ruleForm.smtLayer, // 贴片层数(1全，2top，3bottom)
    bomFileId: fileInfo.boomInfo?.fileId, //	Bom文件id
    coordinateFileId: fileInfo.coordinateInfo?.fileId, // 坐标文件id
  };
  if (ruleForm.productType == '1' && selectedOrderedPcbList.value.length > 0) {
    // 已下单pcb订单
    const [{ pcbWidth, pcbLength }] = selectedOrderedPcbList.value;
    params.pcbWidth = pcbWidth;
    params.pcbLength = pcbLength;
  } else {
    params.pcbLength = ruleForm.pcbLength; // 板子长度
    params.pcbWidth = ruleForm.pcbWidth; // 板子宽度
  }
  if (ruleForm.craftsCategory.length > 0) {
    // 选中的工艺信息
    params.craftsCategory = ruleForm.craftsCategory;
  }
  if (ruleForm.serviceCategory.length > 0) {
    // 选中的服务信息
    params.serviceCategory = ruleForm.serviceCategory;
  }
  crmPcbaOrderCalculationAmountAPI(params).then((res) => {
    if (res.code == 200) {
      billInfo.value = res.data;
    }
  });
};

/**
 * 下一步
 * @param {*} formEl
 */
const handleSumbit = async (formEl) => {
  if (selectedOrderedPcbList.value.length > 0 && ruleForm.productType === '1') {
    const [{ orderPcbNumber }] = selectedOrderedPcbList.value;
    if (Number(ruleForm.orderNumber) > orderPcbNumber) {
      ElMessage.error(t('mall.smt_quantity_exceed_pcb_order'));
      return;
    }
  }
  if (!fileInfo.boomInfo) {
    ElMessage.warning(t('mall.bom_file_cannot_be_empty'));
    return;
  }
  if (!boomConfirm.value) {
    ElMessage.warning(t('mall.confirm_bom_file'));
    return;
  }
  if (!fileInfo.coordinateInfo) {
    ElMessage.warning(t('mall.coordinate_file_cannot_be_empty'));
    return;
  }
  if (!coordinateConfirm.value) {
    ElMessage.warning(t('mall.confirm_coordinate_file'));
    return;
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (!ruleForm.agreement) {
        return ElMessage.warning(t('mall.agree_terms_checkbox'));
      }
      orderStore.setSmtOrderInfo({
        ...ruleForm,
        ...fileInfo,
        coordinateConfirm: coordinateConfirm.value,
        boomConfirm: boomConfirm.value,
        selectedOrderedPcbList: selectedOrderedPcbList.value,
      });
      if (ruleForm.matchType === 1) {
        // 快速匹配 BOM备料确认页面
        router.push({
          path: '/quotation',
          query: {
            bomFileId: fileInfo.boomInfo?.fileId,
            patchNum: ruleForm.orderNumber,
            orderNumber: ruleForm.orderNumber,
            bomName: fileInfo.boomInfo.name,
            fileSerial: fileInfo.boomInfo.fileSerial,
            layer: ruleForm.smtLayer,
            beforeOrderType: 'smt',
          },
        });
      } else {
        //下单页面
        router.push({
          path: '/settlement',
          query: {
            matchType: ruleForm.matchType,
          },
        });
      }
    } else {
      nextTick(() => {
        //加个定时器，有可能监测不到页面变化
        let timer = setTimeout(function () {
          scrollToFormError();
          clearTimeout(timer);
        }, 200);
      });
      console.log('error submit!', fields);
    }
  });
};
/**
 * BOOM删除
 */
const handleBoomDelete = () => {
  fileInfo.boomInfo = null;
  boomConfirm.value = false;
};

/**
 * BOOM下载
 */
const handleBoomDownload = (fileInfo) => {
  downloadFile(fileInfo.path, fileInfo.name);
};
/**
 * BOM文件确认
 */
const openBoomConfirm = (fileInfo) => {
  boomConfrimVisible.value = true;
};
/**
 * 坐标文件确认
 */
const handleBoomConfirm = () => {
  boomConfirm.value = true;
  boomConfrimVisible.value = false;
  getPcbQuote();
};

// 清除产品类型数据
const clearProdData = (tabValue) => {
  const clearData = {
    1: () => {
      ruleForm.orderNumber = null;
      orderStore.pcbOrderInfo = {};
      ruleForm.renderData.length = 0;
      userUploadFileName.value = '';
      userUploadFilePath.value = '';
    },
    2: () => {
      ruleForm.orderNumber = null;
      selectedOrderedPcbList.value.length = 0;
      ruleForm.renderData.length = 0;
      userUploadFileName.value = '';
      userUploadFilePath.value = '';
    },
    3: () => {
      ruleForm.orderNumber = null;
      orderStore.pcbOrderInfo = {};
      selectedOrderedPcbList.value.length = 0;
    },
  };

  const oldValue = pendingVal.value;
  const oldProductType = {
    1: () => {
      return !!selectedOrderedPcbList.value.length;
    },
    2: () => {
      return !!Object.keys(orderStore.pcbOrderInfo).length;
    },
    3: () => {
      return !!ruleForm.renderData.length;
    },
  };
  // 有数据才清除数据和提示内容
  if (oldProductType[oldValue]()) {
    // 清除旧数据
    ElMessageBox.confirm(t('mall.switching_product_type_warning'), t('om.Prompts'), {
      confirmButtonText: t('smt.Define'),
      cancelButtonText: t('smt.Cancel'),
      type: 'warning',
    })
      .then(() => {
        clearData[tabValue]();
      })
      .catch(() => {
        ruleForm.productType = pendingVal.value;
      });
  }
};

/**
 * 下载BOM文件模板
 */
const downloadBom = () => {
  standardDocumentsPath().then((res) => {
    if (res.code == 200) {
      downloadFile(res.data.bomLinkPath);
    }
  });
};

/**
 * 坐标文件确认弹窗
 */
const openCoordinateConfirm = () => {
  coordinateConfrimVisible.value = true;
};

/**
 * 坐标文件确认
 */
const handleCoordinateConfirm = () => {
  coordinateConfirm.value = true;
  coordinateConfrimVisible.value = false;
  getPcbQuote();
};

/**
 * 坐标文件删除
 */
const handleCoordinateDelete = () => {
  fileInfo.coordinateInfo = null;
  coordinateConfirm.value = false;
};

/**
 * 坐标文件下载
 */
const handleCoordinateDownload = (fileInfo) => {
  downloadFile(fileInfo.path, fileInfo.name);
};

/**
 * 创建订单
 */
// const createOrder = (obj) => {
//   addSmt(obj).then((res) => {
//     if (res.code === 200) {
//       router.push({
//         path: '/settlement',
//         query: {
//           orderId: data.id,
//         },
//       });
//     } else {
//       ElMessage.error(res.msg);
//     }
//   });
// };

/**
 * 获取尺寸
 * @param {*} data
 */
const getDimensions = (item) => {
  ruleForm.pcbLength = item.h.toFixed(2);
  ruleForm.pcbWidth = item.w.toFixed(2);
};

// 校验贴片数量 是否 大于 pcb订单量
const checkOrderNumber = (value) => {
  // 校验已下单的PCB订单
  const numValue = Number(value);

  const checkPcbIbeOrderNumber = (orderNumber) => {
    if (numValue <= orderNumber) {
      ruleForm.orderNumber = value;
    } else {
      ElMessage.error(`${t('mall.input_value_exceed', { num: orderNumber })}`);
      ruleForm.orderNumber = orderNumber;
    }
  };

  if (ruleForm.productType === '1' && Object.keys(selectedOrderedPcbList.value).length) {
    const orderPcbNumber = selectedOrderedPcbList.value[0].orderPcbNumber;
    checkPcbIbeOrderNumber(orderPcbNumber);
  }
  // 校验IBE定制
  if (ruleForm.productType === '2' && Object.keys(orderStore.pcbOrderInfo).length) {
    const orderNumber = orderStore.pcbOrderInfo.orderNumber;
    checkPcbIbeOrderNumber(orderNumber);
  }
};

// 首页过来获取板子类型
const { productId, boardLayer, pcbLength, pcbWidth, pcbSum } = route.query;
const getLayerData = () => {
  if (productId || boardLayer || pcbLength || pcbWidth || pcbSum) {
    // 商品类型
    ruleForm.productId = productId;
    ruleForm.pcbLength = pcbLength;
    ruleForm.pcbWidth = pcbWidth;
    ruleForm.orderNumber = pcbSum;
    data.boardLayersSum = boardLayer;
  }
  console.log('route', data.boardLayersSum);
};

getLayerData();

/**
 * 编辑地址
 */
// const handleEditAddress = () => {
//   data.addressVisible = true;
// };

// 选中工艺服务
const onChangeSelectedData = (groupData) => {
  // 构造表单校验数据
  Object.keys(groupData).forEach((key) => {
    const valueList = groupData[key].map((item) => item.id);
    const [value] = valueList; // 单选为字符串， 多选为数组集合
    ruleForm[key] = valueList.length === 1 ? value : valueList;
    // 数据变化时，重新触发该字段的校验
    formRef.value.validateField([key]);
  });
  orderStore.setSmtSelectedListMap(groupData);
  console.log('groupData', groupData);
  getSelectedData(groupData);
  // 请求右侧的PCB报价,获取信息
  const { pcbLength, pcbWidth, orderNumber } = ruleForm;
  console.log(pcbLength, pcbWidth, orderNumber);
  if (pcbLength && pcbWidth && orderNumber) {
    getPcbQuote();
  }
  // else {
  //   ElMessage.warning('请先填写板子尺寸、板子数量');
  // }
};

// 处理子组件工艺选中的数据
const getSelectedData = (groupData) => {
  const slectedGroupList = Object.values(groupData);
  const selectedList = slectedGroupList
    .flat()
    .map((item) => ({ ...item, orderNumber: ruleForm.orderNumber }));
  const selectedServiceList = selectedList.filter((item) => 'serviceKey' in item);
  const selectedCraftList = selectedList.filter((item) => 'craftsKey' in item);
  ruleForm.craftsCategory = selectedCraftList;
  ruleForm.serviceCategory = selectedServiceList;
};

/**
 *  选中地址
 */
// const handleSelectedAddress = (item) => {
//   ruleForm.curAddressInfo = item;
// };

/**
 * 打开已下单订单
 */
const reselect = () => {
  visible.value = true;
};

let selectedOrderedPcbList = ref([]); // 选中的历史订单数据

// 格式化订单状态
const formatOrderStatus = (status) => {
  const orderStatusMap = {
    1: t('mall.matching'),
    2: t('mall.pending_payment'),
    3: t('mall.production_confirmation_pending'),
    4: t('mall.in_production'),
    5: t('mall.awaiting_shipment'),
    6: t('mall.awaiting_receipt'),
    7: t('mall.received'),
    8: t('mall.completed'),
    9: t('mall.refunding'),
    10: t('mall.refunded'),
    11: t('mall.cancelled'),
    12: t('mall.deleted'),
  };
  return orderStatusMap[status] || '--';
};

// 下载pcb文件
const downloadPcbFile = () => {
  downloadFile(userUploadFilePath.value);
};

/**
 * 选中的pcb订单
 */
const handleSelectedPcbOrder = (row) => {
  selectedOrderedPcbList.value = [row];
  ruleForm.orderNumber = row.orderPcbNumber;
  ruleForm.pcbLength = row.pcbLength;
  ruleForm.pcbWidth = row.pcbWidth;
  ruleForm.gerberFileId = row.fileVO.id;
};

/**
 * 关闭pcb订单弹窗
 */
const handleClosePcbOrder = () => {
  visible.value = false;
};

const handleChagneMatchType = (type) => {
  ruleForm.matchType = type;
};

/**
 * 跳转pcb下单
 */
const handleNavigateToPcb = () => {
  router.push({
    path: '/pricing/pcb',
    query: {
      whetherPatch: '2',
    },
  });
};

/**
 * gerber上传
 * @param {*} file
 */
const gerberUpload = (file) => {
  if (ruleForm.orderNumber) {
    uploadDocFile({
      fileType: 1,
      quantity: ruleForm.orderNumber,
      file: file,
    }).then((res) => {
      if (res.code === 200) {
        ElMessage.success(t('mall.upload_successful'));
        // fileInfo.gerberInfo = res.data;
        ruleForm.gerberFileId = res.data.fileId;
        getGerberFilelist(res.data.fileId);
        userUploadFileName.value = res.data.name;
        userUploadFilePath.value = res.data.path;
      } else {
        ElMessage.error(res.msg);
      }
    });
  }
};

/**
 * 获取gerber文件列表
 * @param {*} id
 */
const getGerberFilelist = (id) => {
  gerberFilelist(id).then((res) => {
    if (res.code === 200) {
      if (res.data.length > 0) {
        getGerberFileData(res.data);
      } else {
        ElMessage.error(t('mall.no_parsing_data'));
      }
    } else {
      ElMessage.error(res.msg);
    }
  });
};

/**
 * 获取gerber文件数据
 * @param {*} data
 */
const getGerberFileData = (data) => {
  const requestsList = data.map((item) => {
    return getMallFileData(item.gerberFilePath);
  });
  Promise.all(requestsList).then((res) => {
    ruleForm.renderData = res;
    viewRef.value.readFiles(res, data);
  });
};

/**
 * 获取gerber上传文件flie
 * @param {*} flie
 */
const getGerberFlieData = (flie) => {
  gerberUpload(flie);
};

/**
 * bom文件上传
 * @param {*} flie
 */

const getBoomFlieData = (flie) => {
  if (!ruleForm.orderNumber) {
    ElMessage.error(t('mall.select_smt_quantity'));
    scrollToSection('#basicInfor');
    return false;
  }
  isShowBomProgress.value = true;
  uploadDocFile({
    fileType: 2, // 1Gerber，2BOM，3坐标文件
    quantity: ruleForm.orderNumber,
    isUseAlternative: ruleForm.isUseAlternative,
    smtLayer: ruleForm.smtLayer, // 贴片层(1全贴，2顶层，3底层,默认1全贴)
    batchYearLimit: ruleForm.batchYearLimit, // 接受批次(默认0 不限)
    file: flie,
  }).then((res) => {
    if (res.code === 200) {
      ElMessage.success(t('mall.upload_successful'));
      fileInfo.boomInfo = res.data;
      isShowBomProgress.value = false;
      fileInfo.boomInfo.isConfirm = false; //  文件确认状态
    } else {
      ElMessage.error(res.msg);
      isShowBomProgress.value = false;
    }
  });
};

/**
 * 坐标文件上传
 * @param {*} file
 */
const getCoordinateFlieData = (file) => {
  if (file.size > 50 * 1024 * 1024) {
    ElMessage.error(t('mall.upload_file_limit', { num: 50 }));
    return false;
  }
  if (!ruleForm.orderNumber) {
    ElMessage.error(t('smt.PleasenumberOfPatches'));
    scrollToSection('#basicInfor');
    return false;
  }
  isShowCoordinateProgress.value = true;
  uploadDocFile({
    fileType: 3,
    quantity: ruleForm.orderNumber,
    file: file,
  }).then((res) => {
    if (res.code === 200) {
      ElMessage.success(t('mall.upload_successful'));
      fileInfo.coordinateInfo = res.data;
      isShowCoordinateProgress.value = false;

      fileInfo.coordinateInfo.isConfirm = false; //  文件确认状态
    } else {
      ElMessage.error(res.msg);
      isShowCoordinateProgress.value = false;
    }
  });
};

/**
 * 获取bom文件信息
 * @param {*} row
 */
const getBomId = (row) => {
  const boomInfo = {
    fileId: row.id,
    path: row.filePath,
    name: row.fileName,
  };
  fileInfo.boomInfo = boomInfo;
  fileInfo.boomInfo.isConfirm = false; //  文件确认状态
};

/**
 * 打开配单弹框
 */
const openSelectModal = () => {
  bomVisible.value = true;
};

// 语言切换
const onChangeLang = () => {
  initData();
};

// 免责申明跳转
const handleNavToAgreement = () => {
  const lang = appStore.language;
  switch (lang) {
    case 'en':
      router.push({
        path: '/user-agreement/en_US',
      });
      break;
    default:
      router.push({
        path: '/user-agreement',
      });
  }
};

const pendingVal = ref();
watch(
  () => ruleForm.productType,
  (newVal, oldVal) => {
    pendingVal.value = oldVal;
  },
);
</script>

<template>
  <div class="wrapper">
    <!-- 头部 -->
    <smt-header @lang-change="onChangeLang"></smt-header>
    <div class="pricing-pcb container">
      <div class="pricing-pcb-main">
        <el-breadcrumb :separator-icon="ArrowRight" class="f-28" style="padding-bottom: 20px">
          <el-breadcrumb-item>{{ $t('menu.home') }}</el-breadcrumb-item>
          <el-breadcrumb-item>{{ $t('smt.smtQuote') }}</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- <div class="title">
          <img :src="images['line-CPU@2x']" alt="" />
          <span>SMT 在线下单</span>
        </div> -->
        <el-form
          ref="formRef"
          :model="ruleForm"
          :rules="rules"
          hide-required-asterisk
          label-position="left"
          label-width="160px"
        >
          <!-- PCB信息 -->
          <Sections :title="$t('smt.PCBInfo')">
            <el-form-item :label="$t('smt.productType')" prop="product">
              <template #label> {{ $t('smt.productType') }}<Tips content="1" /> </template>
              <!--产品类型  -->
              <el-radio-group
                class="offset-margin"
                v-model="ruleForm.productType"
                @change="clearProdData"
              >
                <el-radio label="1" border>{{ $t('smt.placedPCBOrders') }}</el-radio>
                <el-radio label="2" border>{{ $t('smt.IBECustomizating') }}</el-radio>
                <el-radio label="3" border>{{ $t('smt.ownSupply') }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <div class="pcb-dropdown-box" v-if="ruleForm.productType">
              <!-- 已下单 PCB 订单 -->
              <template v-if="ruleForm.productType == '1'">
                <el-form-item label-width="110px" :label="$t('smt.PCBOrder')" class="sub-form-item">
                  <!-- <Tips content="1" /> -->
                  <el-button
                    class="select-btn"
                    type="plain"
                    :class="tableData.length ? 'reselect' : ''"
                    @click="reselect"
                    >{{
                      selectedOrderedPcbList.length
                        ? $t('mall.select_again')
                        : $t('smt.selectTheOrder')
                    }}
                  </el-button>
                </el-form-item>
                <el-table
                  v-if="selectedOrderedPcbList.length"
                  :data="selectedOrderedPcbList"
                  style="margin: 0 0 0 0; width: 100%"
                >
                  <el-table-column prop="serial" :label="$t('smt.orderNo')" width="180" />
                  <el-table-column prop="orderPcbNumber" :label="$t('mall.order_quantity')" />
                  <el-table-column prop="createTime" :label="$t('smt.Ordertime')" width="180" />
                  <el-table-column prop="fileName" :label="$t('smt.PCBFilename')">
                    <template #default="scope">
                      <div>
                        {{ scope.row.fileVO.fileName }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="productName" :label="$t('pcb.PlateType')" />
                  <el-table-column prop="orderStatus" :label="$t('smt.orderStatus')">
                    <template #default="scope">
                      <div>
                        {{ formatOrderStatus(scope.row.orderStatus) }}
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
              <!-- IBE定制 -->
              <template v-if="ruleForm.productType == '2'">
                <!-- pcb 订单 -->
                <div
                  v-if="Object.values(orderStore.pcbOrderInfo).length > 0"
                  class="pcb-order-card"
                >
                  <p class="card-title">{{ $t('smt.PCBOrder') }}</p>
                  <div class="order-content">
                    <el-row style="height: 30px">
                      <el-col :span="12"
                        ><p class="order-content-title">{{ $t('mall.delivery_and_shipping') }}</p>
                      </el-col>
                      <el-col :span="12"
                        ><p class="order-content-title">{{ $t('mall.price_and_costs') }}</p></el-col
                      >
                    </el-row>
                    <el-row style="height: 30px">
                      <el-col :span="12">
                        <el-form-item :label="`${$t('mall.delivery_time')}:`" label-width="138px">
                          <span class="desc text-red"
                            ><span
                              class="content"
                              v-if="orderStore.pcbOrderInfo.billInfo.deliveryDay"
                            >
                              {{
                                `${orderStore.pcbOrderInfo.billInfo.deliveryDay} - ${
                                  orderStore.pcbOrderInfo.billInfo.deliveryDay + 3
                                } `
                              }}{{ $t('mall.days') }}</span
                            ></span
                          >
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item :label="pricingDesc" label-width="220px">
                          <span class="desc text-red"
                            >{{ orderStore.pcbOrderInfo.billInfo.symbol
                            }}{{ orderStore.pcbOrderInfo.billInfo.craftsServiceAmount || 0 }}</span
                          >
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row style="height: 30px">
                      <el-col :span="12">
                        <el-form-item
                          :label="`${$t('mall.express_delivery')}:`"
                          label-width="138px"
                        >
                          <span class="desc">{{ $t('mall.based_on_actual_time') }}</span>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item :label="`${$t('mall.logistics_fee')}:`" label-width="220px">
                          <span class="desc">{{ $t('mall.based_on_actual_costs') }}</span>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row style="height: 30px">
                      <el-col :span="12">
                        <el-form-item :label="`${$t('mall.shipping_time')}:`" label-width="138px">
                          <span class="desc">{{ $t('mall.based_on_review_time') }}</span>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item :label="`${$t('mall.tax_fee')}:`" label-width="220px">
                          <span class="desc">{{ $t('mall.based_on_actual_costs') }}</span>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                  <div class="estimated-cost">
                    <div class="estimated-cost-price">
                      <div class="estimated-cost-title">{{ $t('mall.estimated_cost') }}</div>
                      <div class="price">
                        ${{ orderStore.pcbOrderInfo.billInfo.craftsServiceAmount }}
                      </div>
                    </div>
                    <el-button
                      class="m-l-24 color-bo"
                      @click="handleNavigateToPcb"
                      style="margin-left: 134px"
                      >{{ $t('pcb.pcbonlineordering') }} >></el-button
                    >
                  </div>
                </div>
                <el-button
                  v-else
                  class="m-l-24 color-bo"
                  @click="handleNavigateToPcb"
                  style="margin-left: 134px"
                  >{{ $t('pcb.pcbonlineordering') }} >></el-button
                >
              </template>
              <template v-if="ruleForm.productType == '3'">
                <el-form-item
                  label-width="110px"
                  :label="`${$t('pcb.pcbfile')}:`"
                  class="sub-form-item"
                >
                  <div>
                    <UpLoad
                      class="smt-upload"
                      :name="
                        !ruleForm.renderData.length ? $t('pcb.UploadPCBfile') : '重新上传PCB文件'
                      "
                      fileType="1"
                      :smdNum="ruleForm.orderNumber"
                      @getFlieData="getGerberFlieData"
                      @scrollToSection="scrollToSection"
                    >
                    </UpLoad>

                    <div style="display: flex; justify-content: center; flex-direction: column">
                      <div class="pcb-file-name" @click="downloadPcbFile">
                        {{ userUploadFileName }}
                      </div>

                      <p class="upload-tips" style="padding-top: 10px">
                        * {{ $t('pcb.Uploadfilesin') }}
                      </p>
                      <!-- <el-link :underline="false" type="primary" @click="downloadBom"
                        >{{t('mall.file_standard_template')}}
                      </el-link> -->
                    </div>
                  </div>
                </el-form-item>
              </template>
            </div>
          </Sections>

          <!-- 基本信息 -->
          <Sections
            :title="$t('smt.generalInfo')"
            :class="showBorder ? 'flash-border' : 'show-border'"
          >
            <div style="margin-bottom: 20px">
              <el-form-item :label="$t('smt.chipLayer')" prop="smtLayer">
                <template #label>
                  <span style="padding-right: 5px; color: red">*</span>
                  {{ $t('smt.chipLayer') }}<Tips content="1" />
                </template>
                <el-radio-group class="offset-margin" v-model="ruleForm.smtLayer">
                  <el-radio label="1" border>{{ $t('smt.topAndBottom') }}</el-radio>
                  <el-radio label="2" border>{{ $t('smt.topPostingOnly') }}</el-radio>
                  <el-radio label="3" border>{{ $t('smt.bottomLayerOnly') }}</el-radio>
                </el-radio-group>
              </el-form-item>
              <!-- 贴片数量 -->
              <el-form-item
                id="basicInfor"
                :label="$t('smt.patchQuantity')"
                prop="orderNumber"
                :rules="[
                  { required: true, message: $t('smt.PleasenumberOfPatches'), trigger: 'blur' },
                ]"
              >
                <template #label>
                  <span style="padding-right: 5px; color: red">*</span>
                  {{ $t('smt.patchQuantity') }}<Tips content="1" />
                </template>

                <el-input
                  v-model="ruleForm.orderNumber"
                  v-number
                  maxlength="8"
                  :placeholder="$t('smt.patchQuantity')"
                  style="width: 160px"
                  :maxlength="8"
                  @input="checkOrderNumber"
                  :disabled="fileInfo.boomInfo || fileInfo.coordinateInfo"
                >
                  <template #suffix>
                    <span>PCS</span>
                  </template>
                </el-input>
                <span class="tips-text">（{{ $t('smt.defaultNumber') }} ）</span>
              </el-form-item>
            </div>
          </Sections>
          <!-- BOM信息 -->
          <Sections :title="$t('smt.BOMInfo')">
            <el-row>
              <el-col :span="12">
                <el-form-item label-width="210">
                  <template #label>
                    <span style="padding-right: 5px; color: red">*</span>
                    <span>{{ $t('mall.accept_alternative_components') }}</span>
                  </template>
                  <el-radio-group v-model="ruleForm.isUseAlternative">
                    <el-radio :label="1">{{ $t('mall.accept') }}</el-radio>
                    <el-radio :label="2">{{ $t('mall.do_not_accept') }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label-width="150">
                  <template #label>
                    <span style="padding-right: 5px; color: red">*</span>
                    <span>{{ $t('mall.accept_the_batch') }}</span>
                  </template>
                  <el-select
                    v-model="ruleForm.batchYearLimit"
                    :placeholder="`${$t('mall.please_select')}${$t('mall.accept_the_batch')}`"
                    style="width: 160px"
                  >
                    <el-option
                      v-for="item in batchList"
                      :key="item.batchValue"
                      :label="item.batchName"
                      :value="item.batchValue"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <div style="padding-bottom: 15px; display: flex">
              <!-- BOM文件 -->
              <div class="boom-upload-box">
                <UpLoadBoom
                  @getFlieData="getBoomFlieData"
                  :smdNum="ruleForm.orderNumber"
                  :name="t('mall.upload_bom_file')"
                  :fileType="'2'"
                  v-if="!fileInfo.boomInfo && !isShowBomProgress"
                >
                  <template #select-btn>
                    <el-button class="select-btn" @click="openSelectModal" plain>{{
                      $t('smt.SelectMatedBOM')
                    }}</el-button>
                  </template>
                </UpLoadBoom>

                <div v-if="isShowBomProgress" class="progress-border">
                  <el-progress
                    :percentage="100"
                    :stroke-width="20"
                    :duration="50"
                    striped
                    striped-flow
                    class="progress"
                  >
                    <span style="font-size: 16px">{{ $t('mall.uploading') }}</span>
                  </el-progress>
                </div>

                <!-- BOM 确认弹窗 -->
                <ConfirmBox
                  v-if="!isShowBomProgress && fileInfo.boomInfo"
                  :fileInfo="fileInfo.boomInfo"
                  @onConfirm="openBoomConfirm"
                  @onDelete="handleBoomDelete"
                  @onDownload="handleBoomDownload"
                  :isConfirm="boomConfirm"
                />
              </div>
              <!-- 坐标文件 确认弹窗 -->
              <div class="coordinate-upload-box">
                <UpLoadCoordinate
                  @getFlieData="getCoordinateFlieData"
                  :smdNum="ruleForm.orderNumber"
                  :name="$t('smt.Uploadcoordinatefile')"
                  fileType="3"
                  v-if="!fileInfo.coordinateInfo && !isShowCoordinateProgress"
                >
                </UpLoadCoordinate>
                <!-- 坐标文件确认弹窗 -->
                <div class="progress-border" v-if="isShowCoordinateProgress">
                  <el-progress
                    :percentage="100"
                    :stroke-width="20"
                    :duration="50"
                    striped
                    striped-flow
                    class="progress"
                  >
                    <span style="font-size: 16px">{{ $t('mall.uploading') }}</span>
                  </el-progress>
                </div>

                <ConfirmBox
                  v-if="!isShowCoordinateProgress && fileInfo.coordinateInfo"
                  class="coordinate-confirm-box"
                  :fileInfo="fileInfo.coordinateInfo"
                  @onConfirm="openCoordinateConfirm"
                  @onDelete="handleCoordinateDelete"
                  @onDownload="handleCoordinateDownload"
                  :isConfirm="coordinateConfirm"
                />
              </div>
            </div>
          </Sections>

          <!-- SMT工艺信息 -->
          <Sections :title="$t('mall.smt_process')" v-if="data.craftsList.length > 0">
            <el-form-item
              :rules="formItemRule(item, 'craftsName')"
              v-for="item in data.craftsList"
              :key="item.id"
              :label="item.craftsName"
              :prop="item.id"
              class="smt-crafts"
            >
              <template #label>
                <span v-if="item.requiredSelect === 1" style="padding-right: 5px; color: red"
                  >*</span
                >
                {{ item.craftsName }}
                <Tips :title="item.craftsName" :content="item.remark" />
              </template>
              <group-select-tree
                ref="craftsRef"
                :parentData="item"
                :tree-data="item.children"
                @selected="onChangeSelectedData"
              />
            </el-form-item>
          </Sections>

          <!-- 基础服务 -->
          <Sections :title="$t('smt.Basicservices')" v-if="data.baseServieList.length">
            <el-form-item
              :rules="formItemRule(item, 'serviceName')"
              v-for="item in data.baseServieList"
              :key="item.id"
              :prop="item.id"
              class="basic-service"
            >
              <template #label>
                <span v-if="item.requiredSelect === 1" style="padding-right: 5px; color: red"
                  >*</span
                >
                {{ item.serviceName }}
                <Tips :title="item.serviceName" :content="item.remark" />
              </template>
              <group-select-tree
                ref="craftsRef"
                :parentData="item"
                :tree-data="item.children"
                :props="{ optionName: 'serviceName' }"
                @selected="onChangeSelectedData"
              />
            </el-form-item>
          </Sections>
          <!-- 工艺服务 -->
          <Sections :title="$t('mall.process_service')" v-if="data.craftServideList.length">
            <el-form-item
              :rules="formItemRule(item, 'serviceName')"
              v-for="item in data.craftServideList"
              :key="item.id"
              :prop="item.id"
              class="basic-service"
            >
              <template #label>
                <span v-if="item.requiredSelect === 1" style="padding-right: 5px; color: red"
                  >*</span
                >
                {{ item.serviceName }}
                <Tips :title="item.serviceName" :content="item.remark" />
              </template>
              <group-select-tree
                ref="craftsRef"
                :parentData="item"
                :tree-data="item.children"
                :props="{ optionName: 'serviceName' }"
                @selected="onChangeSelectedData"
              />
            </el-form-item>
          </Sections>

          <!-- 定制服务 -->
          <Sections :title="$t('smt.Customizedservices')" v-if="data.customizedServiceList.length">
            <el-form-item
              :rules="formItemRule(item, 'serviceName')"
              v-for="item in data.customizedServiceList"
              :key="item.id"
              :prop="item.id"
              class="basic-service"
            >
              <template #label>
                {{ item.serviceName }}
                <Tips :title="item.serviceName" :content="item.remark" />
              </template>
              <group-select-tree
                ref="craftsRef"
                :parentData="item"
                :tree-data="item.children"
                :props="{ optionName: 'serviceName' }"
                @selected="onChangeSelectedData"
              />
            </el-form-item>
          </Sections>
          <!-- 快递方式 -->
          <!-- <Sections :title="$t('smt.Expressway')">
            <div class="block-wrap" id="expressDelivery">
              <el-form-item prop="expressDelivery">
                <template #label> {{ $t('smt.Expressway') }}<Tips content="1" /> </template>
                <el-row class="row-item">
                  <el-radio-group v-model="ruleForm.expressDelivery">
                    <el-radio
                      v-for="(item, index) in data.expressDeliveryList"
                      :key="index"
                      :label="item.id"
                      @change="handleExpressDeliveryChange(item)"
                      >{{ item.name }}</el-radio
                    >
                  </el-radio-group>
                </el-row>
              </el-form-item>
            </div>
          </Sections> -->
          <!-- <Sections :title="$t('smt.Shippingaddress')">
            <div class="block-wrap">
              <div class="title-wrap">
                <div class="flex">
                  <el-form-item prop="address">
                    <template #label>
                      {{ $t('smt.Selectshippingaddress') }}<Tips content="1" />
                    </template>
                    <div class="text">
                      <span>{{ expressAddress }}</span>
                    </div>
                  </el-form-item>
                </div>
                <div class="edit-btn" @click="handleEditAddress()">
                  <img
                    class="edit-icon"
                    src="@/assets/images/icons/icon_edit.svg"
                    width="18"
                    height="18"
                  />
                  <span>选择</span>
                </div>
              </div>
            </div>
          </Sections> -->

          <!-- 匹配选项方式 -->
          <Sections :title="$t('mall.matching_options_method')">
            <div class="matching-wrap">
              <div
                class="matching-radio-box"
                :class="ruleForm.matchType === 1 ? 'active' : ''"
                @click="handleChagneMatchType(1)"
              >
                <img class="img_1" src="@/assets/images/pricing/matching_icon_1@2x.png" />
                <div class="matching-content">
                  <p class="matching-title">{{ $t('mall.quick_match_type_selection') }}</p>
                  <p class="matching-desc">{{ $t('mall.quick_match_pros') }}</p>
                  <p class="matching-desc">{{ $t('mall.quick_match_cons') }}</p>
                </div>
              </div>
              <div
                class="matching-radio-box"
                :class="ruleForm.matchType === 2 ? 'active' : ''"
                @click="handleChagneMatchType(2)"
              >
                <img class="img_2" src="@/assets/images/pricing/matching_icon_2@2x.png" />
                <div class="matching-content">
                  <p class="matching-title">{{ $t('mall.deep_match_type_selection') }}</p>
                  <p class="matching-desc">{{ $t('mall.deep_match_pros') }}</p>
                  <p class="matching-desc">{{ $t('mall.deep_match_cons') }}</p>
                </div>
              </div>
            </div>
          </Sections>
        </el-form>
      </div>

      <!-- 右侧记价容器 -->
      <div>
        <View3D
          ref="viewRef"
          v-show="ruleForm.renderData.length > 0"
          @getDimensions="getDimensions"
        />
        <div class="summary-box">
          <div class="summary-box-title-wrap">
            <img src="@/assets/images/icons/icon-bill@2x.png" />
            <h2 class="summary-box-title">{{ $t('smt.SmartQuote') }}</h2>
          </div>
          <div class="summary-box-content">
            <!-- 价格费用 -->
            <div class="summary-box-content-item">
              <p class="summary-title">{{ $t('mall.delivery_and_shipping') }}</p>
              <div class="content-item">
                <p class="label">{{ $t('mall.delivery_time') }}</p>
                <p class="desc" v-if="billInfo.deliveryDay">
                  {{ `${billInfo.deliveryDay} - ${billInfo.deliveryDay + 3} `
                  }}{{ $t('mall.days') }}
                </p>
              </div>
              <div class="content-item">
                <p class="label">{{ $t('mall.express_delivery') }}</p>
                <p class="desc">{{ $t('mall.based_on_actual_time') }}</p>
              </div>
              <div class="content-item">
                <p class="label">{{ $t('mall.shipping_time') }}</p>
                <p class="desc">{{ $t('mall.based_on_actual_time') }}</p>
              </div>
            </div>
            <!-- 计价项 -->
            <div class="summary-box-content-item">
              <p class="summary-title">{{ $t('mall.price_and_costs') }}</p>
              <div class="content-item">
                <p class="label">{{ $t('mall.pcb_cost') }}</p>
                <p class="desc price">{{ billInfo.symbol }}{{ pcbAmount }}</p>
              </div>
              <div class="content-item">
                <p class="label">{{ $t('mall.smt_processing_fee') }}</p>
                <p class="desc price">
                  {{ billInfo.symbol }}{{ billInfo.bomMachiningAmount || 0 }}
                </p>
              </div>
              <div class="content-item">
                <p class="label">{{ $t('mall.smt_process_service_fee') }}</p>
                <p class="desc price">
                  {{ billInfo.symbol }}{{ billInfo.craftsServiceAmount || 0 }}
                </p>
              </div>
              <div class="content-item">
                <p class="label">{{ $t('mall.bom_cost') }}</p>
                <p class="desc price">{{ billInfo.symbol }}{{ billInfo.bomAmount || 0 }}</p>
              </div>
              <div class="content-item">
                <p class="label">{{ $t('mall.logistics_fee') }}</p>
                <p class="desc">{{ $t('mall.based_on_actual_costs') }}</p>
              </div>
              <div class="content-item">
                <p class="label">{{ $t('mall.tax_fee') }}</p>
                <p class="desc">{{ $t('mall.based_on_actual_costs') }}</p>
              </div>
            </div>
            <!-- 总计 -->
            <div class="summary-total-box">
              <div class="summary-total-item">
                <p class="total-label">{{ $t('mall.estimated_cost') }}</p>
                <p class="total-price price">{{ billInfo.symbol }}{{ estimatedCost.toFixed(2) }}</p>
              </div>
              <div
                class="summary-total-desc"
                style="margin-top: -5px; margin-bottom: 10px; color: red"
              >
                {{ $t('mall.final_cost_subject_to_review') }}
              </div>
            </div>
            <div class="button-wrap">
              <el-button class="submit-btn" type="primary" @click="handleSumbit(formRef)">
                {{ $t('mall.next_step') }}
              </el-button>
              <div class="user-agreement">
                <el-checkbox label="1" size="large" v-model="ruleForm.agreement"
                  ><div style="display: flex; align-items: center">
                    <span>{{ $t('mall.read_disclaimer') }}</span>
                    <el-link type="primary" :href="agreementUrl" target="_blank"
                      >《{{ $t('mall.disclaimer') }}》</el-link
                    >
                  </div>
                </el-checkbox>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部 -->
    <smt-footer></smt-footer>

    <!-- 选择已下单pcb订单弹窗 -->
    <select-pcb-order-dialog
      v-model="visible"
      @selected="handleSelectedPcbOrder"
      @close="handleClosePcbOrder"
    />
    <!-- 选择已配单BOOM弹窗 -->
    <BomSelectModal v-model="bomVisible" @close="bomCancelModal" @selected="getBomId" />

    <!-- BOOM确认弹窗 -->
    <BoomConfirmDialog
      v-if="boomConfrimVisible"
      v-model="boomConfrimVisible"
      :fileInfo="fileInfo.boomInfo"
      :isConfirm="boomConfirm"
      @confirm="handleBoomConfirm"
    />

    <!-- 封装焊点确认弹窗 -->
    <CoordinateConfirmDialog
      v-if="coordinateConfrimVisible"
      v-model="coordinateConfrimVisible"
      :fileInfo="fileInfo.coordinateInfo"
      :isConfirm="coordinateConfirm"
      @confirm="handleCoordinateConfirm"
    />
  </div>
</template>
<style lang="scss" scoped>
.f-20 {
  font-size: 20px;
}
.title {
  display: flex;
  align-items: center;
  padding: 12px 0;
  font-size: 18px;
  font-weight: 700;
  color: var(--mall-text-color-primary);
  img {
    width: 24px;
    height: 24px;
    margin-right: 12px;
  }
}
.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.tips-text {
  color: #ff0000;
  font-size: 10px;
}

.progress-border {
  box-sizing: border-box;
  padding: 26px 18px;
  border-radius: 4px;
  border: 1px solid #d4d4d4;
  position: relative;
  width: 468px;
  height: 180px;
}

.block-title {
  width: 121px;
  color: var(--mall-text-color-primary);
  font-size: 18px;
  font-weight: 500;
}
.block-wrap {
  padding: 0 24px;
  border-bottom: 1px solid #f5f5f5;
  &:last-child {
    border: none;
  }

  .title-wrap {
    display: flex;
    justify-content: space-between;
    &.table-title {
      padding-top: 24px;
      padding-bottom: 12px;
    }
    .block-title {
      width: 121px;
      color: var(--mall-text-color-primary);
      font-size: 18px;
      font-weight: 500;
    }
    .edit-btn {
      display: flex;
      align-items: center;
      cursor: pointer;
      padding-left: 16px;
      font-size: 14px;
      color: #5255fe;
      > img {
        vertical-align: middle;
        width: 18px;
      }
      > a {
        display: inline-block;
        padding-left: 14px;
        color: var(--mall-color-primary);
        font-family: 'SourceHanSansCN';
      }
    }
  }

  .row-item {
    padding-top: 12px;
    color: var(--mall-text-color-primary);
    font-size: 14px;
    display: table-caption;
    .pay-icons-wrap {
      padding-left: 142px;
      .pay-icon {
        height: 24px;
        margin-bottom: 24px;
      }
      .pay-row {
        > img {
          height: 32px;
          margin-right: 12px;
        }
      }
    }
  }
}
.h-70 {
  height: 70px;
}
.h-120 {
  height: 100%;
  object-fit: cover;
}
.m-5 {
  margin-left: 5px;
  margin-right: 5px;
}
.wrapper {
  background: var(--mall-body-bg-color);
}
.pricing-pcb {
  display: flex;
  padding-top: 12px;
  padding-bottom: 72px;

  &.container {
    padding: 20px 240px;
    margin: 0 auto;
  }
  &-main {
    box-sizing: border-box;
    padding: 20px;
    flex: 1;
    width: 1040px;
    margin-right: 20px;
    background: #fff;
    box-sizing: border-box;
    border-radius: 8px;

    // .upload-box {
    //   // padding: 24px;
    //   margin-bottom: 24px;
    //   border-radius: 8px;
    //   background: #f5f5f5;
    //   .upload-tip {
    //     padding-top: 16px;
    //     text-align: center;
    //     color: #a6a6a6;
    //     font-size: 14px;
    //   }
    // }

    .offset-margin {
      // 抵消radio-item底边边距
      margin-bottom: -14px;
    }

    .pcb-radio {
      height: 60px;
      .pcb-radio-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        > img {
          padding-top: 8px;
          width: 60px;
        }
      }
    }
    .color-radio {
      > i {
        &.white {
          border: 1px solid var(--mall-text-color-primary);
        }
        display: inline-block;
        vertical-align: middle;
        width: 16px;
        height: 16px;
        margin-right: 12px;
        border-radius: 50%;
      }
    }
  }

  .summary-box {
    position: sticky;
    top: 90px;
    width: 302px;
    border-radius: 10px;
    background: #ffffff;
    font-size: 12px;
    font-weight: 500;
    font-family: 'SourceHanSansCN';
    &-title-wrap {
      padding: 0 22px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #e5e5e5;
      > img {
        width: 15px;
        height: 17px;
        margin-right: 12px;
      }
    }
    &-title {
      height: 60px;
      display: flex;
      align-items: center;
      color: var(--mall-text-color-primary);
      font-size: 14px;
      font-weight: 400px;
    }
    &-content {
      &-item {
        padding: 12px;
        border-bottom: 1px solid #e5e5e5;
        .summary-title {
          color: #383838;
          font-size: 14px;
          padding-bottom: 10px;
        }
        .content-item {
          display: flex;
          .label {
            display: inline-block;
            width: 180px;
            color: #686868;
            font-size: 12px;
            padding-bottom: 10px;
          }
          .desc {
            padding-top: 5px;
            color: #888888;
            font-weight: 500;
            font-size: 12px;
          }
          .price {
            color: #ff0000 !important;
            font-size: 12px;
          }
        }
      }

      .summary-item {
        .summary-desc {
          color: #666666;
          font-size: 12px;
          padding-bottom: 10px;
        }
      }

      .button-wrap {
        padding: 4px 12px 12px;
        .submit-btn {
          width: 100% !important;
        }
        ::v-deep .el-button--primary {
          height: 32px !important;
          font-weight: 400;
        }
        .user-agreement {
          display: flex;
          a {
            display: inline-block;
          }
        }
      }
    }
  }

  .summary-total-box {
    padding: 10px 20px 0;
    .summary-total-desc {
      color: #666666;
      font-size: 12px;
    }
    .summary-total-item {
      display: flex;
      padding-bottom: 16px;
    }
    .total-label,
    .total-price {
      padding-top: 6px;
      color: #ff0000;
      font-size: 14px;
    }

    .total-label {
      display: inline-block;
      color: #383838;
      width: 180px;
    }
  }
}

::v-deep .el-upload-dragger {
  background: transparent;
  padding: 0;
  border: 0;
}

::v-deep .el-form {
  .el-form-item {
    margin-bottom: 24px;
    .el-form-item__label {
      font-size: 16px;
      display: flex;
      align-items: center;
    }
  }
}

::v-deep .el-radio-group {
  max-width: 612px;
}

// smt下单样式
.pcb-dropdown-box {
  background: #f5f5f5;
  border-radius: 4px;
  padding: 24px;
  min-height: 172px;
  .sub-form-item {
    ::v-deep .el-form-item__label {
      color: #666666;
      font-size: 14px;
    }

    .pcb-file-name {
      cursor: pointer;
      color: #5255fe;
      text-align: center;
      margin-bottom: -10px;
    }
    .select-btn {
      margin-left: 18px;
    }
  }
}

.smt-crafts ::v-deep .el-form-item__error,
.basic-service ::v-deep .el-form-item__error {
  margin-top: -8px;
}

//  PCB订单样式

.pcb-order-card {
  border-radius: 5px;
  border: 1px solid #d4d4d4;
  background: #ffffff;
  .card-title {
    padding: 0 30px;
    height: 40px;
    line-height: 40px;
    color: #383838;
    font-size: 14px;
    font-family: 'SourceHanSansCN';
    border-bottom: 1px solid #d4d4d4;
  }
  .order-content {
    padding: 0 26px 26px;
    &-title {
      padding: 10px 0 5px;
      color: #383838;
      font-size: 14px;
    }

    ::v-deep .el-form-item {
      margin-bottom: 0;
      &__label {
        color: #686868;
        font-size: 12px;
      }
    }

    .desc {
      color: #686868;
      font-size: 12px;
      &.text-red {
        color: #ff0000;
      }
    }
  }

  .estimated-cost {
    height: 40px;
    border-top: 1px solid #d4d4d4;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 40px;
    .estimated-cost-price {
      display: flex;
      flex-direction: row;
      .estimated-cost-title {
        font-weight: bold;
        margin-right: 10px;
      }
      .price {
        font-weight: bold;
        color: red;
      }
    }
  }
}

.coordinate-upload-box {
  margin-left: 70px;
  width: 467px;
  height: 180px;
  .progress {
    margin-top: 60px;
    margin-left: 30px;
  }
  ::v-deep .el-link {
    font-size: 12px;
  }
}

.matching-wrap {
  display: flex;
  justify-content: center;
  // 匹配选项方式
  .matching-radio-box {
    cursor: pointer;
    &:first-child {
      margin-right: 50px;
    }
    &.active {
      border: 1.5px solid #5255fe;
    }
    padding: 0 15px;
    width: 301px;
    height: 133px;
    border-radius: 5px;
    border: 1px solid #d4d4d4;
    display: flex;
    align-items: center;
    .img_1 {
      width: 45px;
      height: 45px;
    }
    .img_2 {
      width: 40px;
      height: 32px;
    }
    .matching-content {
      padding-left: 18px;

      .matching-title {
        color: #383838;
        font-size: 14px;
        font-weight: 500;
      }
      .matching-desc {
        padding-top: 8px;
        color: #686868;
        font-size: 12px;
      }
    }
  }
}

.upload-tips-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  .upload-tips {
    // padding-top: 20px;
    padding-right: 20px;
    width: 350px;
    color: #666666;
    font-size: 10px;
    line-height: 2;
    text-align: center;
    .accept {
      color: #ff0000;
    }
  }
}

.smt-upload {
  border: none;
  padding: 0;
}
.upload-tips {
  text-align: center;
  color: red;
}

::v-deep .el-form-item {
  margin-bottom: 14px !important;
}
.boom-upload-box {
  width: 466px;
  .progress {
    margin-top: 60px;
    margin-left: 30px;
  }
}
</style>
